import $V from './$V';

export default function rvi(price, stdLength, length) {
    let rviValue = $V.init(price.length,50);
    let stdValue = [0], temp1 = [0], temp2 = [0];
    let diffOfPrice = [0];
    for (let i = 0; i < price.length; i++) {
        diffOfPrice[i] = price[i] - price[i - 1];
        stdValue[i] = 0;
        temp1[i] = 0;
        temp2[i] = 0;
    }
    for(let i = stdLength - 1;i < price.length;i++){
        let sum = 0;
        for (let j = i - stdLength + 1; j <= i; j++) {
            sum += price[j];
        }
        const mean = sum / stdLength;
        let stdSum = 0;
        for (let j = i - stdLength; j <= i; j++) {
            stdSum += Math.pow(price[i] - mean, 2);
        }
        stdValue[i] = Math.sqrt(stdSum / (stdLength - 1));
        if (diffOfPrice[i] < 0) {
            temp1[i] = 0;
            temp2[i] = stdValue[i];
        } else {
            temp1[i] = stdValue[i];
            temp2[i] = 0;
        }
    }
    for(let j = length - 1;j < price.length;j++){
        let sum = 0, sum2 = 0;
        for (let i = j - length + 1; i <=j; i++) {
            sum += temp1[i];
            sum2 += temp2[i];
        }
        rviValue[j] = sum / (sum + sum2) * 100;
    }
    return rviValue;
}
